<template>
  <ion-page>
    <ion-header>
      <ion-toolbar>
        <ion-buttons slot="start">
          <ion-button @click="goBack">
            <ion-icon :icon="arrowBackOutline"></ion-icon>
          </ion-button>
        </ion-buttons>
        <ion-title>房东认证</ion-title>
      </ion-toolbar>
    </ion-header>

    <ion-content :fullscreen="true" class="ion-padding">
      <div class="verification-container">
        <!-- 认证说明 -->
        <ion-card class="info-card">
          <ion-card-content>
            <div class="info-header">
              <ion-icon :icon="shieldCheckmarkOutline" color="primary" size="large"></ion-icon>
              <h2>房东身份认证</h2>
            </div>
            <p>为了保障租客权益，请完成房东身份认证。认证通过后即可发布房源信息。</p>
          </ion-card-content>
        </ion-card>

        <!-- 认证表单 -->
        <form @submit.prevent="submitVerification" v-if="!submitted">
          <!-- 姓名 -->
          <ion-item>
            <ion-label position="stacked">姓名 <span class="required">*</span></ion-label>
            <ion-input
              v-model="form.name"
              placeholder="请输入真实姓名"
              :clear-input="true"
              required
            ></ion-input>
          </ion-item>

          <!-- 手机号 -->
          <ion-item>
            <ion-label position="stacked">手机号 <span class="required">*</span></ion-label>
            <ion-input
              v-model="form.phone"
              placeholder="请输入手机号码"
              type="tel"
              :clear-input="true"
              required
            ></ion-input>
          </ion-item>

          <!-- 身份证号码 -->
          <ion-item>
            <ion-label position="stacked">身份证号码 <span class="required">*</span></ion-label>
            <ion-input
              v-model="form.idCard"
              placeholder="请输入身份证号码"
              :clear-input="true"
              required
            ></ion-input>
          </ion-item>

          <!-- 详细地址 -->
          <ion-item>
            <ion-label position="stacked">详细地址 <span class="required">*</span></ion-label>
            <ion-textarea
              v-model="form.address"
              placeholder="请输入详细地址"
              :auto-grow="true"
              :rows=3
              required
            ></ion-textarea>
          </ion-item>

          <!-- 营业执照 -->
          <ion-item button @click="uploadBusinessLicense">
            <ion-label>
              <h3>营业执照</h3>
              <p>{{ form.businessLicense || '点击上传营业执照照片' }}</p>
            </ion-label>
            <ion-icon :icon="cameraOutline" slot="end" color="medium"></ion-icon>
          </ion-item>

          <!-- 个人身份证 -->
          <ion-item button @click="uploadIdCard">
            <ion-label>
              <h3>个人身份证 <span class="required">*</span></h3>
              <p>{{ form.idCardPhoto || '点击上传身份证照片' }}</p>
            </ion-label>
            <ion-icon :icon="cameraOutline" slot="end" color="medium"></ion-icon>
          </ion-item>

          <!-- 验证码 -->
          <ion-item>
            <ion-label position="stacked">验证码 <span class="required">*</span></ion-label>
            <ion-input
              v-model="form.verificationCode"
              placeholder="请输入验证码"
              type="number"
              :maxlength="6"
              required
            ></ion-input>
            <ion-button 
              slot="end" 
              fill="outline" 
              size="small"
              @click="sendVerificationCode"
              :disabled="!canSendCode || codeSending"
            >
              <ion-spinner v-if="codeSending" name="crescent"></ion-spinner>
              <span v-else>{{ codeButtonText }}</span>
            </ion-button>
          </ion-item>

          <!-- 同意条款 -->
          <ion-item>
            <ion-checkbox v-model="form.agreeTerms" slot="start"></ion-checkbox>
            <ion-label>
              我已阅读并同意 
              <a href="#" @click.prevent="showTerms" class="terms-link">《房东认证协议》</a>
            </ion-label>
          </ion-item>

          <!-- 提交按钮 -->
          <ion-button
            expand="block"
            type="submit"
            :disabled="!isFormValid || submitting"
            class="submit-button"
          >
            <ion-spinner v-if="submitting" name="crescent"></ion-spinner>
            <span v-else>提交认证</span>
          </ion-button>
        </form>

        <!-- 提交成功状态 -->
        <div v-if="submitted" class="success-container">
          <ion-icon :icon="checkmarkCircleOutline" color="success" size="large"></ion-icon>
          <h2>认证申请已提交</h2>
          <p>我们将在3-5个工作日内完成审核，请耐心等待。</p>
          <ion-button expand="block" @click="goToHome">返回首页</ion-button>
        </div>
      </div>
    </ion-content>
  </ion-page>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import {
  IonPage,
  IonHeader,
  IonToolbar,
  IonTitle,
  IonContent,
  IonButtons,
  IonButton,
  IonIcon,
  IonCard,
  IonCardContent,
  IonItem,
  IonLabel,
  IonInput,
  IonTextarea,
  IonCheckbox,
  IonSpinner,
  alertController,
  toastController
} from '@ionic/vue'
import {
  arrowBackOutline,
  shieldCheckmarkOutline,
  cameraOutline,
  checkmarkCircleOutline
} from 'ionicons/icons'
import { useUserStore } from '@/stores/user'
import { submitLandlordVerification } from '@/api/auth'

const router = useRouter()
const userStore = useUserStore()

// 表单数据
const form = ref({
  name: '',
  phone: '',
  idCard: '',
  address: '',
  businessLicense: '',
  idCardPhoto: '',
  verificationCode: '',
  agreeTerms: false
})

// 状态管理
const submitting = ref(false)
const submitted = ref(false)
const codeSending = ref(false)
const countdown = ref(0)

// 计算属性
const isFormValid = computed(() => {
  return form.value.name.trim() !== '' &&
         form.value.phone.trim() !== '' &&
         form.value.idCard.trim() !== '' &&
         form.value.address.trim() !== '' &&
         form.value.idCardPhoto !== '' &&
         form.value.verificationCode.trim() !== '' &&
         form.value.agreeTerms
})

const canSendCode = computed(() => {
  return form.value.phone.trim() !== '' && countdown.value === 0
})

const codeButtonText = computed(() => {
  return countdown.value > 0 ? `${countdown.value}s` : '获取验证码'
})

// 返回上一页
const goBack = () => {
  router.back()
}

// 返回首页
const goToHome = () => {
  router.replace('/home')
}

// 上传营业执照
const uploadBusinessLicense = async () => {
  // 模拟文件上传
  const alert = await alertController.create({
    header: '上传营业执照',
    message: '模拟上传功能，点击确定完成上传',
    buttons: [
      {
        text: '取消',
        role: 'cancel'
      },
      {
        text: '确定',
        handler: () => {
          form.value.businessLicense = '营业执照.jpg'
        }
      }
    ]
  })
  await alert.present()
}

// 上传身份证
const uploadIdCard = async () => {
  // 模拟文件上传
  const alert = await alertController.create({
    header: '上传身份证',
    message: '模拟上传功能，点击确定完成上传',
    buttons: [
      {
        text: '取消',
        role: 'cancel'
      },
      {
        text: '确定',
        handler: () => {
          form.value.idCardPhoto = '身份证.jpg'
        }
      }
    ]
  })
  await alert.present()
}

// 发送验证码
const sendVerificationCode = async () => {
  if (!form.value.phone.trim()) {
    const toast = await toastController.create({
      message: '请先输入手机号',
      duration: 2000,
      color: 'warning',
      position: 'top'
    })
    await toast.present()
    return
  }

  codeSending.value = true
  
  // 模拟发送验证码
  setTimeout(async () => {
    codeSending.value = false
    countdown.value = 60
    
    // 开始倒计时
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)

    const toast = await toastController.create({
      message: '验证码已发送，请查收短信（测试码：123456）',
      duration: 3000,
      color: 'success',
      position: 'top'
    })
    await toast.present()
  }, 1000)
}

// 显示条款
const showTerms = async () => {
  const alert = await alertController.create({
    header: '房东认证协议',
    message: '这里是房东认证协议的内容...',
    buttons: ['确定']
  })
  await alert.present()
}

// 提交认证
const submitVerification = async () => {
  if (!userStore.user?.id) {
    const toast = await toastController.create({
      message: '用户信息异常，请重新登录',
      duration: 2000,
      color: 'danger',
      position: 'top'
    })
    await toast.present()
    return
  }

  submitting.value = true

  try {
    const response = await submitLandlordVerification({
      userId: userStore.user.id,
      name: form.value.name.trim(),
      phone: form.value.phone.trim(),
      idCard: form.value.idCard.trim(),
      address: form.value.address.trim(),
      businessLicense: form.value.businessLicense,
      idCardPhoto: form.value.idCardPhoto,
      verificationCode: form.value.verificationCode.trim()
    })

    if (response.success) {
      submitted.value = true
      
      const toast = await toastController.create({
        message: response.message,
        duration: 3000,
        color: 'success',
        position: 'top'
      })
      await toast.present()
    } else {
      throw new Error(response.message || '提交失败')
    }
  } catch (error: any) {
    console.error('认证提交失败:', error)
    
    const alert = await alertController.create({
      header: '提交失败',
      message: error.message || '认证申请提交失败，请重试',
      buttons: ['确定']
    })
    await alert.present()
  } finally {
    submitting.value = false
  }
}

onMounted(() => {
  // 检查登录状态
  if (!userStore.isLoggedIn) {
    router.replace('/login')
    return
  }

  // 预填用户信息
  if (userStore.user?.name) {
    form.value.name = userStore.user.name
  }
})
</script>

<style scoped>
.verification-container {
  max-width: 600px;
  margin: 0 auto;
}

.info-card {
  margin-bottom: 20px;
}

.info-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.info-header h2 {
  margin: 0;
  color: var(--ion-color-primary);
}

.required {
  color: var(--ion-color-danger);
}

.terms-link {
  color: var(--ion-color-primary);
  text-decoration: none;
}

.submit-button {
  margin-top: 20px;
}

.success-container {
  text-align: center;
  padding: 40px 20px;
}

.success-container ion-icon {
  margin-bottom: 20px;
}

.success-container h2 {
  color: var(--ion-color-success);
  margin-bottom: 12px;
}

.success-container p {
  color: var(--ion-color-medium);
  margin-bottom: 30px;
}

ion-item {
  margin-bottom: 16px;
}
</style>
